﻿#region File Description
//-----------------------------------------------------------------------------
// RecorderScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using DPSF;
using DPSF.ParticleSystems;
#endregion

namespace BeatPong
{
    /// <summary>
    /// This screen implements the actual game logic. It is just a
    /// placeholder to get the idea across: you'll probably want to
    /// put some more interesting gameplay in here!
    /// </summary>
    class RecorderScreen : GameScreen
    {
        #region Fields

        ContentManager content;

        KeyboardState previousKeyboardState = Keyboard.GetState();
        public GameSong song;
        Queue<TimeSpan> beats;

        #endregion

        #region Initialization


        /// <summary>
        /// Constructor.
        /// </summary>
        public RecorderScreen()
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
        }


        /// <summary>
        /// Load graphics content for the game.
        /// </summary>
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");

            song = new GameSong();

            song.song = content.Load<Song>("Songs\\Trip_like_I_do");

            beats = new Queue<TimeSpan>();
           
            SongPlayer.StartSong(song);
        }


        /// <summary>
        /// Unload graphics content used by the game.
        /// </summary>
        public override void UnloadContent()
        {
            content.Unload();
        }


        #endregion

        #region Update and Draw


        /// <summary>
        /// Updates the state of the game. This method checks the GameScreen.IsActive
        /// property, so the game will stop updating when the pause menu is active,
        /// or if you tab away to a different application.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            KeyboardState keyboardState = Keyboard.GetState();
            if (keyboardState.IsKeyDown(Keys.F2) && previousKeyboardState.IsKeyUp(Keys.F2))
            {
                beats.Clear();
                SongPlayer.StartSong(song);
            }
            if (keyboardState.IsKeyDown(Keys.Space) && previousKeyboardState.IsKeyUp(Keys.Space))
            {
                beats.Enqueue(SongPlayer.PlayPosition());
            }
            if (keyboardState.IsKeyDown(Keys.F3) && previousKeyboardState.IsKeyUp(Keys.F3))
            {

                int count = beats.Count;
                song.beats = new List<Beat>();

                for (int x = 0; x < count; x++)
                {
                    song.beats.Add(new Beat(beats.Dequeue()));
                }
                XmlSerializer serializer = new XmlSerializer(typeof(GameSong));
                StreamWriter writer = new StreamWriter("SongXML\\Song.xml");
                serializer.Serialize(writer, song);
                writer.Close();
            }
            previousKeyboardState = keyboardState;
        }

       
        
        public static GameSong LoadSong(string xmlpath)
        {
            return LoadSong(xmlpath, null);
        }

        public static GameSong LoadSong(string xmlpath, ContentManager c)
        {
            GameSong song = new GameSong();

            XmlSerializer serializer = new XmlSerializer(typeof(GameSong));
            StreamReader reader = new StreamReader(xmlpath);

            try
            {
                song = (GameSong)serializer.Deserialize(reader);
            }
            catch
            {
            }
            finally
            {
                reader.Close();
                if (c != null)
                {
                    song.song = c.Load<Song>(song.AssetName);
                }
            }
            return song;
        }

        /// <summary>
        /// Lets the game respond to player input. Unlike the Update method,
        /// this will only be called when the gameplay screen is active.
        /// </summary>
        public override void HandleInput(InputState input)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            // Look up inputs for the active player profile.
            int playerIndex = (int)ControllingPlayer.Value;

            KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
            GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];

            // The game pauses either if the user presses the pause button, or if
            // they unplug the active gamepad. This requires us to keep track of
            // whether a gamepad was ever plugged in, because we don't want to pause
            // on PC if they are playing with a keyboard and have no gamepad at all!
            bool gamePadDisconnected = !gamePadState.IsConnected &&
                                       input.GamePadWasConnected[playerIndex];

            if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected)
            {
                SongPlayer.PauseSong();
                ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
            }
            else
            {
                if (SongPlayer.isPaused())
                {
                    SongPlayer.ResumeSong();
                }
                // TODO: Handle player input here
            }
        }


        /// <summary>
        /// Draws the gameplay screen.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            // This game has a blue background. Why? Because!
            ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                               Color.CornflowerBlue, 0, 0);
        }
        #endregion
    }
}
